from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response
from celery_tasks.static_file.tasks import get_detail_html

from goods.models import SKUImage


class ImageSerializer(serializers.ModelSerializer):
    """
    图片序列化器
    """

    # sku在模型类里面存储的字段sku_id
    # sku_id = serializers.IntegerField()

    class Meta:
        model = SKUImage
        fields = "__all__"

    def create(self, validated_data):

        # ｓｅｌｆ获取视图传递的ｒｅｑｕｅｓｔ对象
        # 4.创建fastDFs客户端
        c = Fdfs_client(settings.FASTDFS_PATH)
        # 5.读取图片文件数据
        file = self.context['request'].FILES.get('image')
        # 6.上传图片
        res = c.upload_by_buffer(file.read())
        # 7 .判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response({'error': '图片上传失败'}, status=400)
        img = SKUImage.objects.create(sku=validated_data['sku'], image=res['Remote file_id'])

        # 详情页面静态化
        get_detail_html.delay(img.sku_id)

        return img

    def update(self, instance, validated_data):
        # ｓｅｌｆ获取视图传递的ｒｅｑｕｅｓｔ对象
        # 4.创建fastDFs客户端
        c = Fdfs_client(settings.FASTDFS_PATH)
        # 5.读取图片文件数据
        file = self.context['request'].FILES.get('image')
        # 6.上传图片
        res = c.upload_by_buffer(file.read())
        # 7 .判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response({'error': '图片上传失败'}, status=400)
        instance.image = image = res['Remote file_id']
        instance.save()
        return instance


class SKUSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
